/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ArkInstanceInvokeExpr, ArkMethod, ArrayType, Stmt } from 'arkanalyzer';
import { BaseChecker, BaseMetaData } from '../BaseChecker';
import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger';
import { Rule, Defects, MethodMatcher, MatcherTypes, MatcherCallback, CheckerUtils } from '../../Index';
import { IssueReport } from '../../model/Defects';

const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'UseCompriseOptimizeCheck');
const indexofSigantrue: string = '@built-in/lib.es5.d.ts: Array.indexOf(T, number)';
const gMetaData: BaseMetaData = {
    severity: 3,
    ruleDocPath: 'docs/use-comprise-optimiz-check.md',
    description: 'Use optimization methods that incorporate checks.'
};

export class UseCompriseOptimizeCheck implements BaseChecker {
    readonly metaData: BaseMetaData = gMetaData;
    public rule: Rule;
    public defects: Defects[] = [];
    public issues: IssueReport[] = [];

    private buildMatcher: MethodMatcher = {
        matcherType: MatcherTypes.METHOD
    };

    public registerMatchers(): MatcherCallback[] {
        const matchBuildCb: MatcherCallback = {
            matcher: this.buildMatcher,
            callback: this.check
        };
        return [matchBuildCb];
    }

    public check = (arkMethod: ArkMethod): void => {
        for (let stmt of arkMethod.getBody()?.getCfg()?.getStmts() ?? []) {
            let invoker = CheckerUtils.getInvokeExprFromStmt(stmt);
            if (!invoker) {
                continue;
            }
            if (!(invoker instanceof ArkInstanceInvokeExpr)) {
                continue;
            }
            let type = invoker.getBase()?.getType();
            if (invoker.getMethodSignature().toString() === indexofSigantrue && type instanceof ArrayType) {
                this.reportIssue(stmt, invoker.getMethodSignature().getMethodSubSignature().getMethodName());
            }
        }
    };

    private reportIssue(stmt: Stmt, keyword: string): void {
        const filePath = stmt.getCfg()?.getDeclaringMethod().getDeclaringArkFile().getFilePath();
        let lineNum = stmt.getOriginPositionInfo().getLineNo();
        let text = stmt.getOriginalText();
        if (!text || text.length === 0) {
            return;
        }
        let startColum = stmt.getOriginPositionInfo().getColNo() + text.indexOf(keyword);
        let endColumn = startColum + keyword.length;
        const severity = this.rule.alert ?? this.metaData.severity;
        let defects = new Defects(lineNum, startColum, endColumn, this.metaData.description, severity,
            this.rule.ruleId, filePath, this.metaData.ruleDocPath, true, false, false);
        this.issues.push(new IssueReport(defects, undefined));
    }
}